package instant.news7;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;
import java.util.List;

import com.iqraaonline.userss.new_userss.R;
import com.iqraaonline.userss.new_userss.databinding.ActivityQuizBinding;

public class QuizActivity extends AppCompatActivity {


    private ActivityQuizBinding binding;
    private List<Question> questionList;
    private int currentQuestionIndex = 0;
    private int score = 0;
    private boolean answered = false;
    private CountDownTimer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityQuizBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        QuizThemes.applyTheme(this);

        binding.backImg.setOnClickListener(view -> {
            onBackPressed();
        });

        String idenT = getIntent().getStringExtra("intent");

        if(idenT.equals("40")){
            questionList = loadGameQuestions();
            displayQuestion();
        } else if (idenT.equals("50")) {
            questionList =   loadAIQuestions();
            displayQuestion();
        } else if (idenT.equals("80")) {
            questionList =   loadJavaProgrammingQuestions();
            displayQuestion();
        }else if (idenT.equals("100")) {
            questionList =   loadPHPProgrammingQuestions();
            displayQuestion();
        } else if (idenT.equals("170")) {
            questionList =   loadAdvancedJavaProgrammingQuestions();
            displayQuestion();
        }

        // Set listeners for options
        binding.option1.setOnClickListener(v -> checkAnswer(binding.option1.getText().toString()));
        binding.option2.setOnClickListener(v -> checkAnswer(binding.option2.getText().toString()));
        binding.option3.setOnClickListener(v -> checkAnswer(binding.option3.getText().toString()));
        binding.option4.setOnClickListener(v -> checkAnswer(binding.option4.getText().toString()));

        // Next button listener
        binding.nextButton.setOnClickListener(v -> {
            if (answered) {
                currentQuestionIndex++;
                if (currentQuestionIndex < questionList.size()) {
                    displayQuestion();
                } else {
                    Toast.makeText(this, "Quiz Finished! Your score: " + score, Toast.LENGTH_LONG).show();
                    resetQuiz();
                }
            } else {
                Toast.makeText(this, "Please select an answer!", Toast.LENGTH_SHORT).show();
            }
        });





    }// OnCrete bundle end here


    private void displayQuestion() {
        answered = false;
        Question currentQuestion = questionList.get(currentQuestionIndex);

        binding.questionText.setText(currentQuestion.getQuestion());
        binding.option1.setText(currentQuestion.getOption1());
        binding.option2.setText(currentQuestion.getOption2());
        binding.option3.setText(currentQuestion.getOption3());
        binding.option4.setText(currentQuestion.getOption4());

        resetOptionColors();
        stopTimer(); // Stop the current timer, if any
        startTimer(); // Start a new timer
    }

    private void checkAnswer(String selectedOption) {
        answered = true;
        Question currentQuestion = questionList.get(currentQuestionIndex);

        if (selectedOption.equals(currentQuestion.getCorrectAnswer())) {
            score++;
            Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Wrong Answer!", Toast.LENGTH_SHORT).show();
        }

        highlightCorrectAnswer(currentQuestion.getCorrectAnswer());
        stopTimer();
    }

    private void resetOptionColors() {
        binding.option1.setBackgroundResource(R.drawable.button_background);
        binding.option2.setBackgroundResource(R.drawable.button_background);
        binding.option3.setBackgroundResource(R.drawable.button_background);
        binding.option4.setBackgroundResource(R.drawable.button_background);
    }

    private void highlightCorrectAnswer(String correctAnswer) {
        if (binding.option1.getText().toString().equals(correctAnswer)) {
            binding.option1.setBackgroundResource(R.drawable.correct_answer_background);
        }
        if (binding.option2.getText().toString().equals(correctAnswer)) {
            binding.option2.setBackgroundResource(R.drawable.correct_answer_background);
        }
        if (binding.option3.getText().toString().equals(correctAnswer)) {
            binding.option3.setBackgroundResource(R.drawable.correct_answer_background);
        }
        if (binding.option4.getText().toString().equals(correctAnswer)) {
            binding.option4.setBackgroundResource(R.drawable.correct_answer_background);
        }
    }

    private void startTimer() {
        timer = new CountDownTimer(30000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                binding.timerText.setText(String.valueOf(millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                binding.timerText.setText("0");
                answered = true;
                Toast.makeText(QuizActivity.this, "Time's up!", Toast.LENGTH_SHORT).show();

                // Highlight correct answer automatically when time is up
                Question currentQuestion = questionList.get(currentQuestionIndex);
                highlightCorrectAnswer(currentQuestion.getCorrectAnswer());
            }
        };
        timer.start();
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
        }
    }

    private void resetQuiz() {
        currentQuestionIndex = 0;
        score = 0;
        displayQuestion();
    }


    private List<Question> loadGameQuestions() {
        List<Question> questions = new ArrayList<>();
        questions.add(new Question("Which language is most commonly used in game development?", "Java", "Python", "C#", "C++", "C++"));
        questions.add(new Question("Which engine is primarily used for Android game development?", "Unreal Engine", "Cocos2d", "Godot", "Unity", "Unity"));
        questions.add(new Question("Which of the following is a popular game development framework for 2D games?", "CryEngine", "LibGDX", "Unreal Engine", "Unity", "LibGDX"));
        questions.add(new Question("What is the most used game engine for high-quality graphics?", "Godot", "CryEngine", "Unity", "Unreal Engine", "Unreal Engine"));
        questions.add(new Question("Which software is commonly used for 3D modeling in game development?", "Photoshop", "Blender", "Maya", "Autodesk 3ds Max", "Blender"));
        questions.add(new Question("What does the term 'Physics Engine' in game development refer to?", "Rendering graphics", "Simulating physical interactions", "Designing game levels", "Creating 3D models", "Simulating physical interactions"));
        questions.add(new Question("Which language is primarily used for scripting in Unity?", "JavaScript", "C#", "Lua", "Python", "C#"));
        questions.add(new Question("In which software do you typically write game code for Unreal Engine?", "Eclipse", "Visual Studio", "Android Studio", "Xcode", "Visual Studio"));
        questions.add(new Question("What is the main purpose of a game loop?", "Managing assets", "Updating the game state and rendering", "Detecting user input", "Saving game progress", "Updating the game state and rendering"));
        questions.add(new Question("Which of the following is a popular tool for creating sound effects for games?", "FL Studio", "Audacity", "GarageBand", "Logic Pro", "Audacity"));
        questions.add(new Question("What does 'AI' in game development refer to?", "Asset Integration", "Artificial Intelligence used for NPC behavior", "Animation Interface", "Audio Interactivity", "Artificial Intelligence used for NPC behavior"));
        questions.add(new Question("What is the term used for the creation of textures for 3D models in games?", "Baking", "Texturing", "Shading", "Mapping", "Texturing"));
        questions.add(new Question("Which of these game development processes refers to creating interactive elements in the game world?", "Modeling", "Scripting", "Rendering", "Texturing", "Scripting"));
        questions.add(new Question("Which software is widely used for creating 2D game assets?", "ZBrush", "Adobe Photoshop", "Blender", "Autodesk Maya", "Adobe Photoshop"));
        questions.add(new Question("Which of the following is NOT a game engine?", "Photoshop", "Unity", "Unreal Engine", "Godot", "Photoshop"));
        questions.add(new Question("What is the purpose of shaders in game development?", "To animate characters", "To control how objects appear in a game", "To simulate physics", "To create 3D models", "To control how objects appear in a game"));
        questions.add(new Question("What is 'level design' in the context of game development?", "Designing the user interface", "Creating the layout of a game environment", "Designing the characters", "Programming game mechanics", "Creating the layout of a game environment"));
        questions.add(new Question("Which of the following is a major challenge in game development?", "Monetization", "Debugging", "Marketing", "All of the above", "All of the above"));
        return questions;
    }



    private List<Question> loadAIQuestions() {
        List<Question> questions = new ArrayList<>();
        questions.add(new Question("What does AI stand for?", "Artificial Intelligence", "Automated Information", "Active Intelligence", "Augmented Interaction", "Artificial Intelligence"));
        questions.add(new Question("Which of the following is a key characteristic of AI?", "Ability to learn and adapt", "Ability to play games", "Ability to generate art", "Ability to analyze data", "Ability to learn and adapt"));
        questions.add(new Question("Which algorithm is most commonly used for training AI models?", "Neural Networks", "Decision Trees", "Linear Regression", "Support Vector Machines", "Neural Networks"));
        questions.add(new Question("What does 'machine learning' refer to in the context of AI?", "The ability of machines to learn from data", "Machines performing tasks without human input", "The process of programming AI systems", "Machines mimicking human behavior", "The ability of machines to learn from data"));
        questions.add(new Question("Which of the following is a subfield of AI?", "Natural Language Processing", "Quantum Computing", "Robotic Engineering", "Blockchain", "Natural Language Processing"));
        questions.add(new Question("Which company created the AI assistant 'Siri'?", "Apple", "Google", "Amazon", "Microsoft", "Apple"));
        questions.add(new Question("What is the Turing Test used for?", "To evaluate machine intelligence", "To evaluate human intelligence", "To evaluate data processing speed", "To evaluate machine performance", "To evaluate machine intelligence"));
        questions.add(new Question("What is 'deep learning' in AI?", "A subset of machine learning involving neural networks", "Using traditional machine learning algorithms", "Programming AI with rules", "Creating AI systems from scratch", "A subset of machine learning involving neural networks"));
        questions.add(new Question("What is the main purpose of AI in self-driving cars?", "To make decisions based on data from sensors", "To entertain passengers", "To follow pre-set routes", "To navigate streets without a driver", "To make decisions based on data from sensors"));
        questions.add(new Question("What is reinforcement learning in AI?", "Learning by interacting with the environment and receiving feedback", "Learning from supervised data", "Learning by analyzing historical data", "Learning from unsupervised data", "Learning by interacting with the environment and receiving feedback"));
        questions.add(new Question("Which of the following is an example of an AI application?", "Face recognition", "Voice assistants", "Recommendation systems", "All of the above", "All of the above"));
        questions.add(new Question("What does the term 'neural network' refer to in AI?", "A series of algorithms modeled after the human brain", "A database structure used for AI storage", "A network of connected devices", "A method for processing large data sets", "A series of algorithms modeled after the human brain"));
        questions.add(new Question("Which company is known for developing the AI model 'GPT'?", "OpenAI", "Google", "Facebook", "IBM", "OpenAI"));
        questions.add(new Question("What is natural language processing (NLP)?", "The ability of AI to understand and generate human language", "The ability of AI to generate images", "The ability of AI to understand emotions", "The ability of AI to analyze large data", "The ability of AI to understand and generate human language"));
        questions.add(new Question("Which AI technique is used for classification problems?", "Supervised learning", "Reinforcement learning", "Clustering", "Unsupervised learning", "Supervised learning"));
        return questions;
    }

    private List<Question> loadAdvancedJavaProgrammingQuestions() {
        List<Question> questions = new ArrayList<>();
        questions.add(new Question("Which of the following is used to create a thread in Java that can return a result?", "Callable", "Runnable", "Thread", "Executor", "Callable"));
        questions.add(new Question("Which method is used to start a thread in Java?", "start()", "run()", "execute()", "begin()", "start()"));
        questions.add(new Question("What does the 'synchronized' keyword do in Java?", "Ensures that a method or block is accessed by only one thread at a time", "Marks a method for optimization", "Limits access to an object", "Makes a method accessible only in certain conditions", "Ensures that a method or block is accessed by only one thread at a time"));
        questions.add(new Question("What is the main difference between '== ' and '.equals()' in Java?", "'==' checks reference equality, '.equals()' checks object value equality", "'==' checks object value equality, '.equals()' checks reference equality", "'==' checks primitive equality, '.equals()' checks reference equality", "'==' checks reference equality, '.equals()' checks both", "'==' checks reference equality, '.equals()' checks object value equality"));
        questions.add(new Question("What will the following Java code print?\nSystem.out.println(2 + 3 + \"Hello\");", "5Hello", "Hello5", "23Hello", "Hello23", "5Hello"));
        questions.add(new Question("Which of these is an immutable class in Java?", "String", "StringBuilder", "ArrayList", "HashMap", "String"));
        questions.add(new Question("Which interface does the 'Iterator' implement?", "Iterable", "Collection", "List", "Queue", "Iterable"));
        questions.add(new Question("In Java, what is the result of trying to access an index outside the bounds of an array?", "ArrayIndexOutOfBoundsException", "NullPointerException", "IndexOutOfBoundsException", "RuntimeException", "ArrayIndexOutOfBoundsException"));
        questions.add(new Question("What is the correct way to define a generic method in Java?", "public <T> void method(T param){}", "public void <T> method(T param){}", "public <T> void method(T param);", "void <T> method(T param){", "public <T> void method(T param){}"));
        questions.add(new Question("What is the purpose of the transient keyword in Java?", "To prevent serialization of a field", "To mark a field for garbage collection", "To make a field accessible only within the current class", "To lock a variable during multi-threading", "To prevent serialization of a field"));
        questions.add(new Question("Which of the following classes are part of the Java Collections Framework?", "ArrayList, HashSet, LinkedList", "String, Integer, Double", "Thread, Runnable, Callable", "File, URL, Socket", "ArrayList, HashSet, LinkedList"));
        questions.add(new Question("Which method is used to get a specific element from a HashMap in Java?", "get()", "find()", "retrieve()", "fetch()", "get()"));
        questions.add(new Question("What does the Java 'clone()' method do?", "Creates a shallow copy of an object", "Creates a deep copy of an object", "Creates a new reference to an object", "Compares two objects", "Creates a shallow copy of an object"));
        questions.add(new Question("Which class can be used to implement a thread-safe map in Java?", "ConcurrentHashMap", "HashMap", "Hashtable", "TreeMap", "ConcurrentHashMap"));
        questions.add(new Question("What is the purpose of the 'finalize()' method in Java?", "To perform cleanup before an object is garbage collected", "To prevent the object from being garbage collected", "To create a clone of the object", "To define the behavior of an object", "To perform cleanup before an object is garbage collected"));
        questions.add(new Question("What is the output of the following Java code?\nString str = \"Hello\";\nstr.concat(\" World\");\nSystem.out.println(str);", "Hello", "Hello World", "World", "Hello World Hello", "Hello"));
        return questions;
    }

    private List<Question> loadJavaProgrammingQuestions() {
        List<Question> questions = new ArrayList<>();
        questions.add(new Question("Which of the following is a valid way to declare a variable in Java?", "int x;", "int x", "x int;", "x: int;", "int x;"));
        questions.add(new Question("What is the default value of a boolean variable in Java?", "false", "true", "0", "null", "false"));
        questions.add(new Question("Which method is the entry point for a Java application?", "main()", "start()", "run()", "execute()", "main()"));
        questions.add(new Question("Which of these is used to terminate a loop in Java?", "break", "continue", "exit", "stop", "break"));
        questions.add(new Question("In Java, which keyword is used to inherit a class?", "extends", "super", "this", "inherits", "extends"));
        questions.add(new Question("Which of the following is NOT a primitive data type in Java?", "String", "int", "char", "float", "String"));
        questions.add(new Question("What does the 'final' keyword do in Java?", "Defines constants or prevents modification", "Makes a method synchronized", "Allows variable reassignment", "Marks a class as abstract", "Defines constants or prevents modification"));
        questions.add(new Question("Which of the following is the correct way to create a new object in Java?", "new MyClass();", "MyClass new = new MyClass();", "new = new MyClass();", "new MyClass()", "new MyClass();"));
        questions.add(new Question("What is the default value of an integer variable in Java?", "0", "null", "undefined", "1", "0"));
        questions.add(new Question("Which of the following is used to handle exceptions in Java?", "try-catch", "throw-catch", "catch-finally", "catch-try", "try-catch"));
        questions.add(new Question("Which collection class is part of Java's Collection Framework and implements List?", "ArrayList", "HashSet", "TreeSet", "HashMap", "ArrayList"));
        questions.add(new Question("Which of the following is the correct way to write a comment in Java?", "// This is a comment", "/ This is a comment /", "<!-- This is a comment -->", "/* This is a comment */", "// This is a comment"));
        questions.add(new Question("Which Java feature helps in hiding the complexity of the system and shows only necessary details?", "Abstraction", "Encapsulation", "Inheritance", "Polymorphism", "Abstraction"));
        questions.add(new Question("Which of the following is used to create a thread in Java?", "Thread class", "Runnable interface", "Callable interface", "Executor framework", "Thread class"));
        questions.add(new Question("What is the result of the following expression in Java: 10 % 3?", "1", "2", "3", "0", "1"));
        questions.add(new Question("Which of the following is used to convert a primitive type to its corresponding wrapper class in Java?", "Autoboxing", "Unboxing", "Parsing", "Casting", "Autoboxing"));
        return questions;
    }


    private List<Question> loadPHPProgrammingQuestions() {
        List<Question> questions = new ArrayList<>();
        questions.add(new Question("What does PHP stand for?", "PHP: Hypertext Preprocessor", "Personal Home Page", "Preprocessor Hypertext Page", "Private Home Page", "PHP: Hypertext Preprocessor"));
        questions.add(new Question("Which of the following is the correct way to include a file in PHP?", "include('file.php');", "import('file.php');", "load('file.php');", "require('file.php');", "include('file.php');"));
        questions.add(new Question("What does the `$_POST` superglobal in PHP do?", "Collects data sent via HTTP POST method", "Collects data sent via HTTP GET method", "Stores session data", "Holds uploaded files", "Collects data sent via HTTP POST method"));
        questions.add(new Question("Which of the following is used to start a PHP session?", "session_start();", "start_session();", "begin_session();", "session_init();", "session_start();"));
        questions.add(new Question("What is the correct way to define a constant in PHP?", "define('CONSTANT', 'value');", "constant('CONSTANT', 'value');", "const('CONSTANT', 'value');", "constant_define('CONSTANT', 'value');", "define('CONSTANT', 'value');"));
        questions.add(new Question("Which function in PHP is used to open a file?", "fopen()", "file_open()", "open_file()", "file_opening()", "fopen()"));
        questions.add(new Question("What is the default port number for a MySQL connection?", "3306", "8080", "443", "80", "3306"));
        questions.add(new Question("Which of the following is NOT a valid PHP data type?", "integer", "boolean", "object", "double-precision", "double-precision"));
        questions.add(new Question("What does the `isset()` function do in PHP?", "Checks if a variable is set and is not null", "Checks if a variable is empty", "Sets a variable", "Checks if a variable is numeric", "Checks if a variable is set and is not null"));
        questions.add(new Question("How can you get the length of a string in PHP?", "strlen($string);", "length($string);", "size($string);", "str_length($string);", "strlen($string);"));
        questions.add(new Question("Which of the following is used to connect to a MySQL database in PHP?", "mysqli_connect()", "mysql_connect()", "connect_mysql()", "pdo_connect()", "mysqli_connect()"));
        questions.add(new Question("What is the correct way to write a comment in PHP?", "// This is a comment", "# This is a comment", "/* This is a comment */", "All of the above", "All of the above"));
        questions.add(new Question("What is the purpose of the `$_SESSION` superglobal in PHP?", "Stores session variables", "Stores cookie values", "Stores HTTP headers", "Stores form data", "Stores session variables"));
        questions.add(new Question("Which PHP function is used to redirect a user to another page?", "header('Location: page.php');", "redirect('page.php');", "move('page.php');", "go('page.php');", "header('Location: page.php');"));
        questions.add(new Question("How can you concatenate two strings in PHP?", "$string1 . $string2", "$string1 + $string2", "$string1 & $string2", "$string1,$string2", "$string1 . $string2"));
        return questions;
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    // Question class
    private static class Question {
        private final String question;
        private final String option1;
        private final String option2;
        private final String option3;
        private final String option4;
        private final String correctAnswer;

        public Question(String question, String option1, String option2, String option3, String option4, String correctAnswer) {
            this.question = question;
            this.option1 = option1;
            this.option2 = option2;
            this.option3 = option3;
            this.option4 = option4;
            this.correctAnswer = correctAnswer;
        }

        public String getQuestion() {
            return question;
        }

        public String getOption1() {
            return option1;
        }

        public String getOption2() {
            return option2;
        }

        public String getOption3() {
            return option3;
        }

        public String getOption4() {
            return option4;
        }

        public String getCorrectAnswer() {
            return correctAnswer;
        }
    }
}